package com.example.cardgame

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.GridView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.concurrent.TimeUnit

class GameActivity : AppCompatActivity() {

    private lateinit var cardGame: CardGame
    private lateinit var gridView: GridView
    private lateinit var adapter: CardAdapter
    private lateinit var timerView: TextView
    private lateinit var countdownTimer: CountDownTimer
    private var timeLeftInMillis: Long = 0
    private var score: Int = 0

    private val initialTimeInMinutes: Long = 3 // 初始时间，3分钟
    private val penaltySeconds: Long = 30 // 每次匹配失败减少的时间（秒数）

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game)

        // 初始化游戏逻辑
        cardGame = CardGame(6)
        gridView = findViewById(R.id.gridview)
        timerView = findViewById(R.id.timer_view)

        // 设置 Adapter 和 GridView
        adapter = CardAdapter(this, cardGame.cards)
        gridView.adapter = adapter

        // 初始化剩余时间
        timeLeftInMillis = TimeUnit.MINUTES.toMillis(initialTimeInMinutes)

        // 设置倒计时
        startTimer()

        // 设置点击监听器
        gridView.setOnItemClickListener { _, _, position, _ ->
            val result = cardGame.flipCard(position)
            when (result) {
                FlipResult.Flipped, FlipResult.MatchFound -> {
                    // 更新界面
                    adapter.notifyDataSetChanged()
                    // 检查是否所有卡片都已匹配
                    if (cardGame.allCardsMatched) {
                        gameOver()
                    }
                }
                FlipResult.NoMatch -> {
                    // 更新界面
                    adapter.notifyDataSetChanged()
                    // 执行惩罚，减少时间
                    reduceTime(penaltySeconds)
                }
                else -> { /* 不需要处理 */ }
            }
        }
    }

    // 启动倒计时
    private fun startTimer() {
        countdownTimer = object : CountDownTimer(timeLeftInMillis, 1000) {

            override fun onTick(millisUntilFinished: Long) {
                timeLeftInMillis = millisUntilFinished
                updateTimerView()
            }

            override fun onFinish() {
                timeLeftInMillis = 0
                updateTimerView()
                gameOver()
            }
        }.start()
    }

    // 更新显示的时间
    private fun updateTimerView() {
        val minutes = TimeUnit.MILLISECONDS.toMinutes(timeLeftInMillis)
        val seconds = TimeUnit.MILLISECONDS.toSeconds(timeLeftInMillis) % 60
        timerView.text = String.format("%02d:%02d", minutes, seconds)
    }

    // 减少时间的函数
    private fun reduceTime(seconds: Long) {
        // 减少剩余时间
        timeLeftInMillis -= TimeUnit.SECONDS.toMillis(seconds)

        if (timeLeftInMillis <= 0) {
            timeLeftInMillis = 0
            gameOver()
        }

        // 重新启动倒计时
        countdownTimer.cancel()
        startTimer()

        // 更新时间显示
        updateTimerView()
    }

    // 游戏结束处理
    private fun gameOver() {
        countdownTimer.cancel()
        // 计算分数（剩余秒数）
        score = (timeLeftInMillis / 1000).toInt()

        // 显示游戏结束对话框
        AlertDialog.Builder(this)
            .setTitle(getString(R.string.game_over))
            .setMessage(getString(R.string.final_score, score))
            .setPositiveButton(getString(R.string.restart)) { _, _ ->
                // 重新开始游戏
                restartGame()
            }
            .setNegativeButton(getString(R.string.return_to_main)) { _, _ ->
                // 返回主界面，并返回分数
                returnScoreToMainActivity()
            }
            .setCancelable(false)
            .show()
    }

    // 重新开始游戏
    private fun restartGame() {
        // 重置游戏状态
        cardGame = CardGame(6)
        adapter = CardAdapter(this, cardGame.cards)
        gridView.adapter = adapter
        adapter.notifyDataSetChanged()

        // 重置并启动计时器
        timeLeftInMillis = TimeUnit.MINUTES.toMillis(initialTimeInMinutes)
        countdownTimer.cancel()
        startTimer()
    }

    // 将分数返回给 MainActivity
    private fun returnScoreToMainActivity() {
        val intent = Intent().apply {
            putExtra("finalScore", score)
        }
        setResult(RESULT_OK, intent)
        finish()
    }

    override fun onBackPressed() {
        // 返回时需要停止计时器
        countdownTimer.cancel()
        super.onBackPressed()
    }
}
